package cn.yhr.summerboot.web;

import org.apache.catalina.Context;
import org.apache.catalina.Host;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Wrapper;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;

/**
 * @auther yhr
 * @create 2019-05-28 15:16
 * @todo
 */
public class WebServletContainer {

    private int port;

    public void run() throws LifecycleException {
        //1.把目录的绝对路径获取到
        String classPath = System.getProperty("user.dir");

        //2.新建一个Tomcat对象
        Tomcat tomcat = new Tomcat();

        //3.创建一个连接器
        Connector connector = tomcat.getConnector();
        //4.连接器有一个端口属性
        connector.setPort(port);
        connector.setURIEncoding("UTF-8");

        //5.设置Host
        Host host = tomcat.getHost();
        //6.设置Host的属性，可以参照Server.xml来进行理解
        host.setName("localhost");
        host.setAppBase("templates");


        //7.把class加载进来，把启动的工程加入进来了
        Context context = tomcat.addContext(host,"/",classPath);

        if(context instanceof StandardContext) {
            StandardContext standardContext = (StandardContext) context;
            //要给一个默认的web.xml文件
            //standardContext.setDefaultContextXml("C:\\Program Files\\Apache Software Foundation\\Tomcat 7.0\\conf\\web.xml");
            //把server设置进去
            Wrapper wrapper = tomcat.addServlet("/","DispatcherServlet",new DispatcherServlet());
            wrapper.addMapping("/");
        }
        tomcat.start();
        //强制Tomcat Server等待，避免main线程执行结束后关闭
        tomcat.getServer().await();
    }
}
